package web;

import bean.Grade;
import bean.Student;
import service.GradeService;
import service.StudentService;
import service.impl.GradeServiceImpl;
import service.impl.StudentServiceImpl;
import util.PageUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/Educational/student/studentServlet")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if("insert".equals(method)){
            insert(req,resp);
        }else if("update".equals(method)){
            update(req, resp);
        }else if("findbyid".equals(method)){
            findbyid(req, resp);
        }else if("delete".equals(method)){
            deletestu(req, resp);
        }else{
            findlist(req, resp);
        }
    }

    //删除学员
    //删除有两种，一种是真删除，一种是假删除即修改表中状态那列的值
    protected void deletestu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        //根据主键查询学生信息
        StudentService service=new StudentServiceImpl();
        int i = service.delStu(sid);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(i>0){
            writer.println("<script>alert('删除成功');location.href='/Educational/student/studentServlet'</script>");
        }else{
            writer.println("<script>alert('删除失败');location.href='/Educational/student/studentServlet'</script>");
        }
    }
    //新增学员
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将参数封装到学生对象中
        Student student = new Student();
        student.setStuNo(req.getParameter("stuNo"));
        student.setStuName(req.getParameter("stuName"));
        student.setGid(Integer.parseInt(req.getParameter("gid")));
        student.setSex(Integer.parseInt(req.getParameter("sex")));
        student.setEmail(req.getParameter("email"));
        student.setPhone(req.getParameter("phone"));
        student.setRegistered(req.getParameter("registered"));
        student.setAddress(req.getParameter("address"));
        student.setPolitics(req.getParameter("politics"));
        student.setIdNumber(req.getParameter("idNumber"));
        student.setProfession(req.getParameter("profession"));
        student.setIntrodction(req.getParameter("introdction"));
        //日期和state状态在dao层赋值，这里新增功能的表单没有这两个属性
        System.out.println("新增学员:"+student);
        //调取service
        StudentService service=new StudentServiceImpl();
        int i = service.insertStu(student);
        System.out.println("i值:"+i);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //新增成功后不能直接跳转到list.jsp,需要去studentServlet中重新查询列表后再走list.jsp，否则页面没有数据
            writer.println("<script>alert('新增成功');location.href='/Educational/student/studentServlet'</script>");
        }else{
            //新增失败后不能直接跳转到add.jsp，因为每进入add.jsp页面一次，需要去数据库查询年级下拉列表值，需要去getGradeList查询后再携带req跳转add.jsp
            writer.println("<script>alert('新增失败');location.href='/Educational/student/getGradeList'</script>");
        }

    }
    //主键查询
    protected void findbyid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String sid = req.getParameter("sid");
        System.out.println("要修改的学员id"+sid);
        //根据主键查询学生信息
        StudentService service=new StudentServiceImpl();
        Student student = service.findById(Integer.parseInt(sid));
        System.out.println("待修改的学员信息:"+student);
        //查询年级列表
        GradeService gradeService=new GradeServiceImpl();
        List<Grade> list = gradeService.getList();
        //将年级列表和学生返回页面用于数据回显
        req.setAttribute("glist",list);
        req.setAttribute("stu",student);
        req.getRequestDispatcher("edit.jsp").forward(req,resp);
    }
    //模糊查询+分页查询
    protected void findlist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取参数
        //1.1 获取模糊查询的条件参数
        String stuname = req.getParameter("stuname");
        System.out.println(stuname);
        String stuno = req.getParameter("stuno");
        String sex = req.getParameter("sex");
        //1.2 获取分页查询的当前页码值和每页显示的记录数   分页语法:limit 开始位置,显示条数
        String pageIndex = req.getParameter("pageIndex"); //页码值(当前页码值)
        //如果页面没有传入pageIndex的值，则认为默认查询第一页
        int index=pageIndex==null?1:Integer.parseInt(pageIndex);
        //2.调取service方法
        PageUtil pageUtil = new PageUtil();
        StudentService service=new StudentServiceImpl();
        int usex=(sex==null||sex.length()==0?-1:Integer.parseInt(sex));
        List<Student> students = service.getStudents(stuname,stuno,usex,index,pageUtil.getPageSize());
        System.out.println("分页查询的结果集:"+students);
        int total = service.total(stuname,stuno,usex);//基于模糊查询获取查询的总条数
        pageUtil.setTotal(total);
        System.out.println("分页查询的总条数:"+total);
        //获取总页数=总条数%每页显示的条数>0?总条数/每页显示条数+1:总条数/每页显示条数
        //下面这个公式是固定的，把它移到PageUtil工具中的getTotalPages()方法中，以后使用直接掉这个方法
        //int totalPages=total%pageUtil.getPageSize()>0?total/pageUtil.getPageSize()+1:total/pageUtil.getPageSize();
        pageUtil.setTotalPages(pageUtil.getTotalPages());//将模糊查询的总条数和总页数存入分页工具中
        pageUtil.setDataList(students);//将查询结果集和当前页码值存入分页工具pageUtil中
        pageUtil.setPageIndex(index);
        //3.跳转页面
        //存储模查条件值，在页面回显
        req.setAttribute("stuname",stuname);
        req.setAttribute("stuno",stuno);
        req.setAttribute("sex",sex);
        req.setAttribute("p1",pageUtil);
        //将分页数据pageUtil存入req，和模查条件值一起传给前台，
        //摸查主要用来在模查框中回显模查条件
        //分页数据将查询结果集返回页面展示，将当前页码值返回页面，用于上一页(页码值-1)、下一页(页码值+1)
        req.getRequestDispatcher("list.jsp").forward(req,resp);
    }
    //修改学员
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数，封装到对象中
        Student stu = new Student();
        int sid = Integer.parseInt(req.getParameter("sid"));
        System.out.println("update的sid是"+sid);
        stu.setStuId(sid);
        stu.setStuNo(req.getParameter("stuNo"));
        stu.setStuName(req.getParameter("stuName"));
        stu.setGid(Integer.parseInt(req.getParameter("gid")));
        stu.setSex(Integer.parseInt(req.getParameter("sex")));
        stu.setEmail(req.getParameter("email"));
        stu.setPhone(req.getParameter("phone"));
        stu.setRegistered(req.getParameter("registered"));
        stu.setAddress(req.getParameter("address"));
        stu.setPolitics(req.getParameter("politics"));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date regDate = null;
        try {
            regDate = sdf.parse(req.getParameter("regDate"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("servlet中更新的regDate："+regDate);
        stu.setRegDate(regDate);
        stu.setState(Integer.parseInt(req.getParameter("state")));
        stu.setIdNumber(req.getParameter("idNumber"));
        stu.setProfession(req.getParameter("profession"));
        stu.setIntrodction(req.getParameter("introdction"));
        System.out.println("servlet中待更新的stu："+stu);
        StudentService service=new StudentServiceImpl();
        int i = service.updateStu(stu);
        System.out.println("servlet中更新受影响:"+i);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if(i>0){
            //修改成功后到studentServlet重新查询数据库所有数据然后在list.jsp中显示
            writer.println("<script>alert('更新成功');location.href='/Educational/student/studentServlet'</script>");
        }else{
            //修改失败，到studentServlet?method=findbyid&sid="+sid+"中获取该id对象，并跳转到edit.jsp中回显
            writer.println("<script>alert('更新失败');location.href='/Educational/student/studentServlet?method=findbyid&sid="+sid+"'</script>");
        }
    }
}
